<template>
  <!--xs:小于576px，每列占24格，即一行-->
  <!--md:大于等于768px，每列占12格，即一行两列-->
  <a-row :gutter="[24, 24]">
    <!--题目展示区-->
    <a-col :xs="24" :md="12">
      <a-tabs :active-key="activeKey" @change="handleTabsChange" lazy-load>
        <a-tab-pane key="question" title="题目">
          <a-card
            :title="questionInfo?.title"
            :bordered="false"
            class="questionInfoCard"
          >
            <template #extra>
              <a-space>
                <span v-for="(tag, index) in questionInfo?.tags" :key="index">
                  <a-tag v-if="tag === '简单'" class="tagsList" color="#00b42a">
                    {{ tag }}
                  </a-tag>
                  <a-tag
                    v-else-if="tag === '中等'"
                    class="tagsList"
                    color="#ffb400"
                  >
                    {{ tag }}
                  </a-tag>
                  <a-tag
                    v-else-if="tag === '困难'"
                    class="tagsList"
                    color="#f53f3f"
                  >
                    {{ tag }}
                  </a-tag>
                  <a-tag v-else class="tagsList" color="#86909c">
                    {{ tag }}
                  </a-tag>
                </span>
              </a-space>
            </template>
            <a-descriptions title="判题配置" :column="{ xs: 1, md: 2, lg: 3 }">
              <a-descriptions-item>
                时间限制（ms）
                <a-tag>{{ questionInfo?.judgeConfig.timeLimit }}</a-tag>
              </a-descriptions-item>
              <a-descriptions-item>
                内存限制（KB）
                <a-tag>{{ questionInfo?.judgeConfig.memoryLimit }}</a-tag>
              </a-descriptions-item>
              <a-descriptions-item>
                堆栈限制（KB）
                <a-tag>{{ questionInfo?.judgeConfig.stackLimit }}</a-tag>
              </a-descriptions-item>
            </a-descriptions>
            <MdViewer :value="questionInfo?.content" />
          </a-card>
        </a-tab-pane>
        <a-tab-pane key="comment" title="讨论">
          <Comment :comment-list="commentList" :load-data="getCommentList" />
        </a-tab-pane>
        <a-tab-pane key="answer" title="题解">
          <Editor :value="questionAnswer" mode="tab" />
        </a-tab-pane>
      </a-tabs>
    </a-col>
    <!--代码编辑区-->
    <a-col :xs="24" :md="12">
      <!--编程语言下拉框-->
      <strong> 编程语言：</strong>
      <a-select
        v-model="submitForm.language"
        :style="{ width: '200px' }"
        placeholder="请选择编程语言"
      >
        <a-option value="java">Java</a-option>
        <a-option value="cpp">C++</a-option>
        <a-option value="html">HTML</a-option>
        <a-option disabled>其他语言敬请期待...</a-option>
      </a-select>
      <!--代码编辑器-->
      <MonacoEditor
        :code="submitForm.code as String"
        :language="submitForm.language as String"
        :handle-change="changeCode"
        :readonly="false"
      />
      <!--提交按钮-->
      <div class="submitBtn">
        <a-button
          type="primary"
          status="success"
          style="width: 130px"
          @click="submitCode"
          :disabled="countdown > 0"
          v-if="countdown === 0"
          >提交
        </a-button>
        <a-button v-else type="primary" status="success" style="width: 130px">
          {{ `${countdown} 秒后重试` }}
        </a-button>
      </div>
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
import { useRoute } from "vue-router";
import {
  QuestionControllerService,
  QuestionSubmitAddRequest,
} from "../../../generated";
import { onMounted, provide, ref } from "vue";
import { Message } from "@arco-design/web-vue";
import MonacoEditor from "@/components/MonacoEditor.vue";
import MdViewer from "@/components/MdViewer.vue";
import Comment from "@/components/Comment.vue";
import comment from "@/components/Comment.vue";
import { Editor } from "@bytemd/vue-next";

const route = useRoute();

// 激活的tab
const activeKey = ref("question");

// 评论列表
const commentList: any = ref([]);

// 题目答案
let questionAnswer: any = ref("");

/**
 * 处理Tabs的切换
 * @param key 当前激活的Tabs
 */
const handleTabsChange = (key: string) => {
  // 当前激活的key
  activeKey.value = key;
  // 根据不同的key选择触发不同的函数
  switch (key) {
    case "comment":
      getCommentList();
      break;
    case "answer":
      getAnswer();
      break;
  }
};

/**
 * 获取评论列表
 */
const getCommentList = async () => {
  const res = await QuestionControllerService.getQuestionCommentByIdUsingGet(
    questionId as any
  );
  if (res.code === 0) {
    commentList.value = res.data;
  } else {
    Message.error("获取评论信息失败！");
  }
};

/**
 * 获取题目答案
 */
const getAnswer = async () => {
  const res = await QuestionControllerService.getAnswerByQuestionIdUsingGet(
    questionId as any
  );
  if (res.code === 0) {
    questionAnswer.value = res.data;
  } else {
    Message.error("获取题解信息失败");
  }
};

// 题目id
const questionId = route.params.questionId;

// 父组件向子组件（评论组件）传值
provide("questionId", questionId);

// 题目信息
const questionInfo = ref();

// 提交按钮禁用倒计时
const countdown = ref(0);

/**
 * 提交的表单数据
 */
const submitForm = ref<QuestionSubmitAddRequest>({
  language: "java",
  code:
    "public class Main {\n" +
    "    public static void main(String[] args) {\n" +
    "        \n" +
    "    }\n" +
    "}",
  questionId: questionId as any,
});

/**
 * 代码编辑器值变化时触发
 * @param value 代码编辑器内容
 */
const changeCode = (value: string) => {
  submitForm.value.code = value;
};

/**
 * 加载题目数据
 */
const loadData = async () => {
  const res = await QuestionControllerService.getQuestionVoByIdUsingGet(
    questionId as any
  );
  if (res.code === 0) {
    questionInfo.value = res.data;
  } else {
    Message.error("获取题目信息失败，" + res.message);
  }
};

/**
 * 提交代码
 */
const submitCode = async () => {
  // 再次提交倒计时
  countdown.value = 60;
  // 开始倒计时
  const timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      // 倒计时结束
      clearInterval(timer);
      countdown.value = 0; // 重置倒计时的值
    }
  }, 1000);

  // 发生提交请求
  const res = await QuestionControllerService.doSubmitUsingPost(
    submitForm.value
  );
  if (res.code === 0) {
    Message.success("提交成功，请回提交记录页查看结果");
  } else {
    Message.error("代码提交失败，" + res.message);
  }
};

/*组件挂载完成，调用加载题目数据*/
onMounted(() => {
  loadData();
});
</script>

<style scoped>
/*题目信息卡片*/
.questionInfoCard {
  height: 68vh;
  overflow: auto;
}

/*提交按钮*/
.submitBtn {
  display: flex;
  align-items: center;
  justify-content: end;
  margin-top: 10px;
}

/*修改原有卡片样式的标题*/
:deep(.arco-card-header-title) {
  font-weight: 700;
  font-size: 26px !important;
}
</style>